const JobIntention = require('../models/JobIntention');
const { Op } = require('sequelize');

// 创建或更新求职意向
exports.upsertJobIntention = async (req, res) => {
  try {
    const userId = req.user.id;
    const intentionData = { ...req.body, userId };

    // 查找用户是否已有求职意向
    let intention = await JobIntention.findOne({ where: { userId } });

    if (intention) {
      // 更新现有求职意向
      intention = await intention.update(intentionData);
      return res.status(200).json({
        success: true,
        message: '求职意向更新成功',
        data: intention
      });
    } else {
      // 创建新的求职意向
      intention = await JobIntention.create(intentionData);
      return res.status(201).json({
        success: true,
        message: '求职意向发布成功',
        data: intention
      });
    }
  } catch (error) {
    console.error('操作求职意向失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，操作求职意向失败',
      error: error.message
    });
  }
};

// 获取当前用户的求职意向
exports.getMyJobIntention = async (req, res) => {
  try {
    const userId = req.user.id;
    const intention = await JobIntention.findOne({ where: { userId } });

    if (!intention) {
      return res.status(404).json({
        success: false,
        message: '未找到求职意向，请先创建'
      });
    }

    return res.status(200).json({
      success: true,
      data: intention
    });
  } catch (error) {
    console.error('获取求职意向失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取求职意向失败',
      error: error.message
    });
  }
};

// 删除求职意向
exports.deleteJobIntention = async (req, res) => {
  try {
    const userId = req.user.id;
    const deleted = await JobIntention.destroy({ where: { userId } });

    if (deleted === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到求职意向'
      });
    }

    return res.status(200).json({
      success: true,
      message: '求职意向删除成功'
    });
  } catch (error) {
    console.error('删除求职意向失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，删除求职意向失败',
      error: error.message
    });
  }
};

// 管理员获取所有求职意向（用于后台管理）
exports.getAllJobIntentions = async (req, res) => {
  try {
    const { page = 1, limit = 10, status, industry } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

    if (status) whereClause.status = status;
    if (industry) whereClause.industry = { [Op.like]: `%${industry}%` };

    const { count, rows: intentions } = await JobIntention.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['updatedAt', 'DESC']]
    });

    return res.status(200).json({
      success: true,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      data: intentions
    });
  } catch (error) {
    console.error('获取求职意向列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取求职意向列表失败',
      error: error.message
    });
  }
};